<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <title>03_深拷贝-复杂深拷贝</title>
    </head>
    <body>
        <script>
            // (1) JSON.parse(JSON.stringify())
            // 不可以拷贝 undefined、function、正则 等类型

            // (2) 简单深拷贝
            // 不可以拷贝 数组、正则、null 会被拷贝为{}对象

            // (3) 复杂深拷贝
            var obj1 = {
                a1:'zs',
                a2:18,
                a3:true,
                a4:undefined,
                a5:null,
                a6:[1,2,3],
                a7:function(){
                    console.log(111);
                },
                a8:{name:'ls'},
                a9:/\w{6,8}/
            }

            function deepCopy(target){
                var result;

                if(typeof target === 'object'){
                    // 有4种情况等于obj  数组 正则  null 和对象
                    if(target instanceof Array){
                        result = [];
                        for(var i = 0; i < target.length; i++){
                            result.push(target[i]);
                        }

                    }else if(target == null){
                        result = null;
                        
                    }else if(target instanceof RegExp){
                        result = target;
                    }else {
                        // 对象
                        result = {};
                        for(var x in target){
                            result[x] = typeof target[x] === 'object' ? deepCopy(target[x]) : target[x];
                        }
                    }
                }else{
                    // 处理的函数
                    result = target;
                }

                return result;

            }

           var obj2 = deepCopy(obj1);
           console.log(obj1);
           console.log(obj2);

           obj1.a6[1] = 666;
           console.log(obj1);
           console.log(obj2);
        </script>
    </body>
</html>